<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <text class="title">经营数据</text>
      <view class="time-filter">
        <button class="time-button" :class="{'active': currentDate === '昨日'}" @click="setDateRange('yesterday')">昨日</button>
          <button class="time-button" :class="{'active': currentDate === '本周'}" @click="setDateRange('week')">本周</button>
          <button class="time-button" :class="{'active': currentDate === '本月'}" @click="setDateRange('month')">本月</button>
          <button class="time-button" :class="{'active': currentDate === '自定义'}" v-if="currentDate === '自定义'">自定义</button>
      </view>
    </view>

    <!-- 日期选择器 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">选择日期范围</text>
      </view>
      <view class="date-range-picker" style="position: relative;z-index: 100;">
        <uni-datetime-picker 
          @show="showPicker = true"
          @maskClick="showPicker = false"
          type="daterange" 
          :start-placeholder="dateRange[0]"
          :end-placeholder="dateRange[1]"
          :start-date="dateRange[0]" 
          :end-date="dateRange[1]" 
          @change="handleDateRangeChange"
        />
      </view>
    </view>

    <!-- 数据概览卡片 -->
    <view class="stats-grid">
      <view class="stats-item">
        <text class="stats-label">总订单</text>
        <text class="stats-value">{{ overviewData.orderCount }}</text>
      </view>
      <view class="stats-item">
        <text class="stats-label">总收入</text>
        <text class="stats-value">¥{{ overviewData.totalIncome }}</text>
      </view>
    </view>

    <!-- 销售数据图表 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">销售趋势</text>
      </view>
      <view class="chart-container">
        <qiun-data-charts 
          v-show="!showPicker"
          type="line" 
          :chartData="salesChartData" 
          :opts="chartOptions.line"
          :canvas2d="true"
          :ontouch="true"
          canvasId="salesChart"
        />
      </view>
    </view>


    <!-- 热销商品排行 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">热销商品TOP10</text>
      </view>
      <view class="chart-container">
        <qiun-data-charts 
          v-show="!showPicker"
          type="bar"
          :chartData="hotGoodsChartData"
          :opts="chartOptions.bar"
          :canvas2d="true"
          canvasId="hotGoodsChart"
        />
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getBusinessDataOverview, getBusinessDataCharts } from '@/api/businessData';
import { useUserStore } from '@/store/user';

const userStore = useUserStore();
const showPicker = ref(false)

const currentDate = ref('昨日');
const dateRange = ref([]);
const overviewData = ref({
  orderCount: 0,
  totalIncome: 0
});

const setDateRange = (type) => {
  console.log('setDateRange', type)
  const today = new Date();
  const yesterday = new Date(today);
  yesterday.setDate(today.getDate() - 1);
  const startDate = new Date();
  
  if (type === 'yesterday') {
    currentDate.value = '昨日';
    dateRange.value = [formatDate(yesterday), formatDate(yesterday)];
  } else if (type === 'week') {
    currentDate.value = '本周';
    // 计算本周一（周一作为周开始）
    const day = startDate.getDay();
    const diff = startDate.getDate() - day + (day === 0 ? -6 : 1); // 调整周日的情况
    startDate.setDate(diff);
    // 本周截止到昨日
    dateRange.value = [formatDate(startDate), formatDate(yesterday)];
  } else if (type === 'month') {
    currentDate.value = '本月';
    // 计算本月第一天
    startDate.setDate(1);
    dateRange.value = [formatDate(startDate), formatDate(today)];
  }
  console.log('setDateRange end', dateRange.value)
  loadData();
};

const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const handleDateRangeChange = (e) => {
  console.log('handleDateRangeChange', e)
  // uni-datetime-picker的change事件返回的是数组格式 [startDate, endDate]
  if (Array.isArray(e) && e.length === 2) {
    dateRange.value = [e[0], e[1]];
    currentDate.value = '自定义';
    loadData();
  }
  showPicker.value = false
  console.log('showPicker', showPicker.value)
};

const loadData = async () => {
  try {
    // 检查是否有商户ID
    if (!userStore.merchantId) {
      uni.showToast({
        title: '商户信息获取失败',
        icon: 'none'
      });
      return;
    }

    // 构建查询参数
    const params = {
      merchantId: parseInt(userStore.merchantId),
      startDate: dateRange.value[0],
      endDate: dateRange.value[1]
    };

    // 并行请求概览数据和图表数据
    const [overviewResult, chartsResult] = await Promise.all([
      getBusinessDataOverview(params),
      getBusinessDataCharts(params)
    ]);

    // 更新概览数据
    overviewData.value = {
      orderCount: overviewResult.data.orderCount || 0,
      totalIncome: overviewResult.data.totalIncome || 0
    };

    // 更新图表数据
    initCharts(chartsResult.data);

  } catch (error) {
    console.error('加载经营数据失败:', error);
    uni.showToast({
      title: '数据加载失败',
      icon: 'none'
    });
    
    // 失败时显示空数据
    overviewData.value = {
      orderCount: 0,
      totalIncome: 0
    };
    initCharts({
      orderTrend: { xAxis: [], series: [] },
      hotGoods: { yAxis: [], series: [] }
    });
  }
};

const salesChartData = ref({
  categories: [],
  series: []
});


const hotGoodsChartData = ref({
  categories: [],
  series: []
});

const initCharts = (chartData) => {
  console.log('initCharts', chartData)
  
  // 智能处理日期格式，为滚动模式优化
  const formatDateForChart = (dateStr) => {
    if (!dateStr) return '';
    
    const date = new Date(dateStr);
    const month = date.getMonth() + 1;
    const day = date.getDate();
    
    // 统一使用简化格式，让滚动功能处理显示逻辑
    return `${month}/${day}`;
  };
  
  const xAxisData = chartData?.orderTrend?.xAxis || [];
  const formattedCategories = xAxisData.map(dateStr => formatDateForChart(dateStr));
  
  // 初始化订单趋势图数据
  salesChartData.value = {
    categories: formattedCategories,
    series: [{
      name: '订单数',
      data: chartData?.orderTrend?.series || []
    }]
  };

  // 初始化热销商品排行数据
  console.log('hotGoods', chartData?.hotGoods)
  hotGoodsChartData.value = {
    categories: chartData?.hotGoods?.yAxis || [],
    series: [{
      name: '销量',
      data: chartData?.hotGoods?.series || []
    }]
  };
};

onLoad(() => {
  // 初始化为昨日数据
  setDateRange('yesterday');
});


const chartOptions = ref({
  line: {
    color: ['#ff6b6b'],
    padding: [20, 15, 0, 15],
    enableScroll: true, // 开启图表拖拽功能
    xAxis: { 
      type: 'grid',
      gridType: 'dash',
      fontSize: 12,
      itemCount: 4, // x轴单屏显示数据的数量，默认为5个
      scrollShow: true, // 显示滚动条，默认false
      scrollAlign: 'left', // 滚动条初始位置
      scrollBackgroundColor: '#F7F7FF', // 滚动条背景色
      scrollColor: '#DEE7F7' // 滚动条颜色
    },
    extra: { 
      line: { type: 'curve' },
      tooltip: {
        showBox: true,
        showArrow: true,
        showCategory: true
      }
    }
  },
  pie: {
    color: ['#ff6b6b', '#ff9a9e', '#975FE5', '#FAC858', '#91CB74'],
    legend: { position: 'right' },
    extra: { pie: { label: true }}
  },
  bar: {
    color: ['#ff6b6b'],
    xAxis: { 
      disableGrid: true,
      fontSize: 12
    },
    yAxis: { gridType: 'dash' }
  }
});
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.time-filter {
  display: flex;
  align-items: center;
  padding: 10rpx 20rpx;
  background: #f7f7f7;
  border-radius: 30rpx;
  font-size: 26rpx;
  color: #666;
  gap: 10rpx;
}

.time-button {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  background: transparent;
  color: #666;
  border: 1rpx solid transparent;
  transition: all 0.3s ease;
  
  &.active {
    background: linear-gradient(to right, #ff9a9e, #ff6b6b);
    color: #fff;
    box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.3);
  }
  
  &:active {
    transform: scale(0.95);
  }
}

.date-range-picker {
  display: flex;
  align-items: center;
  padding: 15rpx 20rpx;
  background: #f7f7f7;
  border-radius: 16rpx;
  font-size: 28rpx;
  color: #666;
  z-index: 9999;
}

.date-range-picker text {
  margin: 0 10rpx;
}

.overview-cards {
  display: flex;
  justify-content: space-between;
  margin: 30rpx 0;
}

.card {
  flex: 1;
  padding: 30rpx;
  background: #fff;
  border-radius: 16rpx;
  text-align: center;
  margin-right: 20rpx;

  &:last-child {
    margin-right: 0;
  }
}

.card-title {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.card-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.chart-container {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 30rpx;
}

.chart-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.chart {
  width: 100%;
  height: 400rpx;
}

.section {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 30rpx;
}

.section-header {
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.hot-goods {
  padding: 10rpx 0;
}

.hot-goods-item {
  display: flex;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1px solid #f5f5f5;
}

.hot-goods-item:last-child {
  border-bottom: none;
}

.rank {
  width: 40rpx;
  height: 40rpx;
  line-height: 40rpx;
  text-align: center;
  background: #f0f0f0;
  border-radius: 50%;
  margin-right: 20rpx;
  font-size: 24rpx;
  color: #666;
}

.hot-goods-item:nth-child(1) .rank {
  background: #FF9500;
  color: #fff;
}

.hot-goods-item:nth-child(2) .rank {
  background: #FF2D55;
  color: #fff;
}

.hot-goods-item:nth-child(3) .rank {
  background: #5AC8FA;
  color: #fff;
}

.name {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.sales {
  font-size: 26rpx;
  color: #999;
}

.stats-grid {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 24rpx;
  margin: 32rpx 0 40rpx 0;
}

.stats-item {
  flex: 1;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 24rpx 0 rgba(0,0,0,0.06);
  padding: 36rpx 0 32rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: box-shadow 0.2s;
}

.stats-item:not(:last-child) {
  margin-right: 0;
}

.stats-label {
  font-size: 26rpx;
  color: #888;
  margin-bottom: 10rpx;
  letter-spacing: 1rpx;
}

.stats-value {
  font-size: 40rpx;
  font-weight: bold;
  color: #ff6b6b;
  margin-bottom: 0;
}

/* 图表容器样式 */
.chart-container {
  height: 350px;
  width: 100%;
}

/* 响应式适配 */
@media screen and (max-width: 750rpx) {
  .chart-container {
    height: 320px;
  }
}
</style>
